package com.xinyuan.trade.Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xinyuan.trade.R;
import com.xinyuan.trade.Activity.InfoListActivity;
import com.xinyuan.trade.Adapter.DynamicAdapter;
import com.xinyuan.trade.Adapter.NewAdapter;
import com.xinyuan.trade.Entity.BackGroundEntity;
import com.xinyuan.trade.Entity.DynamicEntity;
import com.xinyuan.trade.Entity.NewEntity;
import com.xinyuan.trade.Listener.RequestWebListener;
import com.xinyuan.trade.Net.NetUtils;
import com.xinyuan.trade.Net.NetUtils.NetCallBack;
import com.xinyuan.trade.Utils.Config;
import com.xinyuan.trade.Utils.Utils;
import com.xinyuan.trade.Widght.CustomListView;
import com.xinyuan.trade.Widght.LoadingView;
import com.xinyuan.trade.Widght.ScrollViewExtend;
import com.xinyuan.trade.Widght.autoscrollviewpager.AutoScrollViewPager;
import com.xinyuan.trade.Widght.autoscrollviewpager.ImagePagerAdapter;

/**
 * 首页
 * 
 * @author daiy
 * 
 */
public class HomeFragment extends BaseFragment implements OnClickListener {

	private Resources resources;
	private ScrollViewExtend layout_scroll;
	private LoadingView layout_loading;
	private AutoScrollViewPager viewpager;
	private LinearLayout mNumLayout;
	private Button mPreSelectedBt;
	private TextView tv_news_more;
	private CustomListView listview_new;
	private TextView tv_trends_more;
	private CustomListView listview_dynamic;
	private NewAdapter newadapter;
	private DynamicAdapter dynamicadapter;
	private RelativeLayout layout_top;
	private TextView tv_top;
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_home, container, false);

		resources = getResources();

		initView(v);
		initData();

		return v;
	}

	private void initView(View v) {
		layout_top = (RelativeLayout) v.findViewById(R.id.layout_top);
		uiAdapter.setMargin(layout_top, LayoutParams.MATCH_PARENT, 60, 0, 0, 0, 0);
		
		tv_top = (TextView) v.findViewById(R.id.tv_top);
		uiAdapter.setTextSize(tv_top, 26);
		
		layout_scroll = (ScrollViewExtend) v.findViewById(R.id.layout_scroll);
		layout_loading = (LoadingView) v.findViewById(R.id.layout_loading);

		viewpager = (AutoScrollViewPager) v.findViewById(R.id.viewpager);
		uiAdapter.setMargin(viewpager, LayoutParams.MATCH_PARENT, 228, 0, 0, 0,
				0);

		mNumLayout = (LinearLayout) v.findViewById(R.id.ll_pager_num);
		uiAdapter.setMargin(mNumLayout, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, 0, 190, 0, 0);

		tv_news_more = (TextView) v.findViewById(R.id.tv_news_more);
		tv_news_more.setOnClickListener(this);

		listview_new = (CustomListView) v.findViewById(R.id.listview_new);
		
		newadapter = new NewAdapter(mActivity);

		tv_trends_more = (TextView) v.findViewById(R.id.tv_trends_more);
		tv_trends_more.setOnClickListener(this);

		listview_dynamic = (CustomListView) v.findViewById(R.id.listview_dynamic);
		
		dynamicadapter = new DynamicAdapter(mActivity);
	}

	private void initData() {
		initBackground();
		initNewList();
		initDynamicList();
	}

	private void initBackground() {
		NetUtils.getValue(mActivity, Config.BACKGROUND, new NetCallBack() {

			@Override
			public void success(String json) {
				layout_scroll.setVisibility(View.VISIBLE);
				layout_loading.postHandle(LoadingView.success);
				layout_loading.setVisibility(View.GONE);
				BackGroundEntity entity = new Gson().fromJson(json,
						BackGroundEntity.class);

				List<BackGroundEntity.Data> data = entity.getData();

				if (data != null && data.size() >= 0) {
					for (int i = 0; i < data.size(); i++) {
						Button bt = new Button(mActivity);
						LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(
								uiAdapter.CalcWidth(12), uiAdapter
										.CalcWidth(12));
						layoutparams.setMargins(uiAdapter.CalcWidth(5), 0,
								uiAdapter.CalcWidth(5), 0);
						bt.setLayoutParams(layoutparams);
						if (i == 0) {
							bt.setBackgroundResource(R.drawable.point);
							mPreSelectedBt = bt;
						} else {
							bt.setBackgroundResource(R.drawable.point_press);
						}
						mNumLayout.addView(bt);
					}

					List<String> photolist = new ArrayList<String>();
					for (BackGroundEntity.Data dat : data) {
						photolist.add(dat.getThumb());
					}

					viewpager.setAdapter(new ImagePagerAdapter(mActivity,
							photolist).setInfiniteLoop(true));
					viewpager
							.setOnPageChangeListener(new MyOnPageChangeListener(
									data.size()));

					viewpager.setInterval(5000);
					viewpager.startAutoScroll();
					viewpager.setCurrentItem(Integer.MAX_VALUE / 2
							- Integer.MAX_VALUE / 2 % data.size());
				}
			}

			@Override
			public void failed(String msg) {
				// System.out.println(msg);
				layout_loading.postHandle(LoadingView.interfaceerror);
				layout_loading.setL(l);
			}
		});
	}
	
	private void initNewList() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("currentpage", "1");
		params.put("pagenum", "5");

		NetUtils.post(mActivity, Config.NEWSBYPAGE, params, new NetCallBack() {

			@Override
			public void success(String json) {
				NewEntity entity = new Gson().fromJson(json, NewEntity.class);

				List<NewEntity.Data> data = entity.getData();
				newadapter.addListEntity(data);
				listview_new.setAdapter(newadapter);
				Utils.setListViewHeightBasedOnChildren(listview_new);
			}

			@Override
			public void failed(String msg) {
				// System.out.println(msg);
			}
		});
	}
	
	private void initDynamicList() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("currentpage", "1");
		params.put("pagenum", "5");

		NetUtils.post(mActivity, Config.COMPANYBYPAGE, params, new NetCallBack() {

			@Override
			public void success(String json) {
				DynamicEntity entity = new Gson().fromJson(json, DynamicEntity.class);

				List<DynamicEntity.Data> data = entity.getData();
				dynamicadapter.addListEntity(data);
				listview_dynamic.setAdapter(dynamicadapter);
				Utils.setListViewHeightBasedOnChildren(listview_dynamic);
			}

			@Override
			public void failed(String msg) {
				// System.out.println(msg);
			}
		});
	}
	
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int imagesize;

		public MyOnPageChangeListener() {

		}

		public MyOnPageChangeListener(int imagesize) {
			this.imagesize = imagesize;
		}

		@Override
		public void onPageSelected(int position) {
			if (mPreSelectedBt != null) {
				mPreSelectedBt.setBackgroundResource(R.drawable.point_press);
			}

			Button currentBt = (Button) mNumLayout.getChildAt(position
					% imagesize);
			currentBt.setBackgroundResource(R.drawable.point);
			uiAdapter.setMargin(currentBt, 12, 12, 5, 0, 5, 0);
			mPreSelectedBt = currentBt;
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	RequestWebListener l = new RequestWebListener() {

		@Override
		public void requestWeb() {
			initData();
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		viewpager.stopAutoScroll();
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(mActivity, InfoListActivity.class);
		switch (v.getId()) {
		case R.id.tv_news_more:
			intent.putExtra(InfoListActivity.SELECT_INDEX, InfoListActivity.newlist_index);
			startActivity(intent);
			mActivity.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			break;
		case R.id.tv_trends_more:
			intent.putExtra(InfoListActivity.SELECT_INDEX, InfoListActivity.dymaniclist_index);
			startActivity(intent);
			mActivity.overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
			break;
		default:
			break;
		}
	};
}
